package xnj.lazydog.btcontroller.ObjectFile;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.DrawableUtils;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.List;

import xnj.lazydog.btcontroller.ControlViews.ControlViews.ControlElement;
import xnj.lazydog.btcontroller.ControlViews.ItemProject;
import xnj.lazydog.btcontroller.ControlViews.Project;

public class ObjectFile {

    private static final String TAG = "ObjectFile";

    private static boolean isInternalSpace = true;


    public static void cd(boolean int_n_ext)
    {
        isInternalSpace = int_n_ext;
    }

    static final String ROOT_DIR_NAME = "BCProjects";
    static final String ROOT_SNAP_DIR_NAME = "snap";

    public static String extRootDir;
    public static String extSnapDir;

    private static void getExtRootDir(Context context){

        File rootDir = context.getExternalFilesDir(ROOT_DIR_NAME);
        File snapDir = context.getExternalFilesDir(ROOT_SNAP_DIR_NAME);

        if(!rootDir.exists())
            rootDir.mkdir();

        if(!snapDir.exists())
            snapDir.mkdir();

        extRootDir = rootDir.getAbsolutePath();
        extSnapDir = snapDir.getAbsolutePath();
    }


    public static boolean saveBitmap(Bitmap bitmap,String fileName)
    {

        File dir_file = new File(extSnapDir);
        if(!dir_file.exists()) {
            if(!dir_file.mkdir())
                return false;
        }

        // 创建图片文件
        File img = new File(dir_file,fileName);
        if(!img.exists())
        {
            try {
                img.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        try {
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(img));
            bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        //       Log.w(TAG, "saveBitmap: "+file.getAbsolutePath()+"/"+dir_name+"/"+name);

        return true;
    }

    public static Drawable getDrawable(String snapName)
    {
        String path = extSnapDir + "/" +snapName;
        File file = new File(path);
        if(file.exists())
            return Drawable.createFromPath(path);
        else
            return null;
    }



    public static void shareProFile(Context context, File file)
    {
        Uri uri;
        if(Build.VERSION.SDK_INT>=24) {
            uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".FileProvider", file);
        }else
        {
            uri = Uri.fromFile(file);
        }
        String type="text/*";

        Intent intent;
        //////////////////////////////// 判断文件的数量，确定是发送单个还是多个

        intent = new Intent(Intent.ACTION_SEND);
        intent.setType(type);
        intent.putExtra(Intent.EXTRA_STREAM,uri);
        ///////////////////////////////// 启动发送Activity
        context.startActivity(Intent.createChooser(intent,"Share"));
    }

    /**  将对象保存到内部文件中
     * @param context
     * @param fileName
     * @param obj
     */
    public static void saveObject(Context context, String fileName, Object obj) {

        getExtRootDir(context);

        Log.w(TAG, "saveObject: "+fileName );
        context.deleteFile(fileName);
        try {
            FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileName = extRootDir +"/"+fileName;

        File sf =  new File(fileName);
        if(!sf.exists()) {
            try {
                sf.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(sf.exists())
        {
            try {

                FileOutputStream outputStream = new FileOutputStream(sf,false);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                objectOutputStream.writeObject(obj);
                objectOutputStream.close();
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        //context.deleteFile(fileName);

    }


    /**  从本地文件加载出对象
     * @param context
     * @param fileName
     * @return
     */
    public static Object loadObject(Context context, String fileName) {
        Object object = null;

        getExtRootDir(context);
        if(isFileExist(context,fileName)) {
            try {
                FileInputStream inputStream = context.openFileInput(fileName);
                ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                object = objectInputStream.readObject();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }else
        {
            fileName = extRootDir + "/" + fileName;
            File sf =  new File(fileName);
            if(sf.exists())
            {
                try {
                    FileInputStream inputStream =  new FileInputStream(sf);
                    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                    object = objectInputStream.readObject();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return object;
    }


    public static Object loadObject(File sf) {
        Object object = null;

        if(sf.exists())
        {
            try {
                FileInputStream inputStream =  new FileInputStream(sf);
                ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                object = objectInputStream.readObject();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }

        return object;
    }

    /**   检查内部文件根目录中某文件是否存在
     * @param context
     * @param fileName
     * @return
     */
    public static boolean isFileExist(Context context,String fileName)
    {
        boolean isOK = false;
        String[] s = context.fileList();
        if(s!=null) {
            for (String ss:s)
            {
                if(fileName.equals(ss))
                    isOK = true;
            }
        }
        return isOK;
    }


    public static long getLongTime()
    {
        return (new Date()).getTime();
    }

    public static void listAllFiles(Context context)
    {
        String []ss = context.fileList();
        for (String s:ss)
        {
            Log.w("FILE","->"+s);
        }
    }


    public static void deleteUselessFiles(Context context,List<ItemProject> ips)
    {
        String[] files = context.fileList();

        for(String s:files)
        {
            if(!hasFile(ips,s)&&!"project_list".equals(s)&&s.contains(".pro"))
            context.deleteFile(s);
        }

        File dir = new File(extRootDir+"/");
        //Log.w(TAG, "deleteUselessFiles: "+dir.exists()+"  "+dir.isDirectory() );
        if(dir.exists()&&dir.isDirectory())
        {
            String[] extFiles = dir.list();

            for(String s:extFiles)
            {
                //Log.w(TAG, "deleteUselessFiles: "+s );
                if(!hasFile(ips,s)&&!"project_list".equals(s)&&s.contains(".pro"))
                {
                    File f = new File(dir,s);
                    f.delete();
                }
            }
        }

        dir = new File(extSnapDir+"/");
        //Log.w(TAG, "deleteUselessFiles: "+dir.exists()+"  "+dir.isDirectory() );
        if(dir.exists()&&dir.isDirectory())
        {
            String[] extFiles = dir.list();

            for(String s:extFiles)
            {
                //Log.w(TAG, "deleteUselessFiles: "+s );
                if(!hasPng(ips,s)&&s.contains(".pro.png"))
                {
                    File f = new File(dir,s);
                    f.delete();
                }
            }
        }


    }

    public static boolean hasFile(List<ItemProject> ips,String fileName)
    {
        boolean has = false;
        if(ips==null)
            return false;
        for(ItemProject ip:ips)
        {
         if(fileName.equals(ip.fileName))
         {
             return true;
         }
        }
            return has;
    }

    public static boolean hasPng(List<ItemProject> ips,String fileName)
    {
        boolean has = false;
        if(ips==null)
            return false;
        for(ItemProject ip:ips)
        {
            if(fileName.contains(ip.fileName))
            {
                return true;
            }
        }
        return has;
    }

    public static String filterFileName(String name)
    {
        /// \ : * " < > | ？
        name = name.replace("<","《");
        name = name.replace(">","《");
        name = name.replace("\\","！");
        name = name.replace(":","：");
        name = name.replace("*","※");
        name = name.replace("\"","”");
        name = name.replace("|","！");
        name = name.replace("/","の");
        name = name.replace("_","-");
        return name.replace("?","？");
    }


    public static String getProjectNewFileName(String beforeFileName,String name,int type)
    {
        String[] ss = beforeFileName.split("_");
        String filteredName = filterFileName(name);
        String Ori = (type==0)?"V":"H";
        return filteredName +"_"+Ori+"_"+ss[2];
    }



}
